const { app, BrowserWindow, ipcMain, Tray, Menu, nativeImage } = require('electron/main')
const path = require('node:path')
const fs = require('fs')
const { exec } = require('child_process'); // 引入child_process模块

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600
  })

  win.loadFile('index.html')
}


function getJsonFiles(dir) {
  let jsonFiles = {};
  fs.readdirSync(dir).forEach(file => {
    if (path.extname(file) === '.jsonl') {
      let filePath = path.join(dir, file);
      let fileContent = fs.readFileSync(filePath, 'utf8');
      const lines = fileContent.split('\n');
      const jsonObjects = lines.map(line => {
          if (line.trim()!== '') {
              return JSON.parse(line);
          }
          return null;
      });
      jsonFiles[file.replace('.jsonl', '')] = jsonObjects.filter(obj => obj!== null);
    }
  });
  return jsonFiles
}

let dataDir = './data'; // 将data目录路径替换为实际路径
let jsonFiles = getJsonFiles(dataDir);
console.log(jsonFiles);

let tray
app.whenReady().then(() => {
  ipcMain.handle('ping', () => 'pong')
  ipcMain.handle('getJsonFiles', () => getJsonFiles(dataDir))
  ipcMain.handle('runPythonScript',() => runPythonScript())
  
  // Menu.setApplicationMenu(null)
  const icon = nativeImage.createFromPath('img/icon.png')
  tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Item1', type: 'radio' },
    { label: 'Item2', type: 'radio' },
    { label: 'Item3', type: 'radio', checked: true },
    { label: 'Item4', type: 'radio' }
  ])

  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)  
  createWindow()
  
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})


async function runPythonScript() {
  const pythonScriptPath = path.join(__dirname, 'python_scripts', 'main.py');
  try {
    const result = await new Promise((resolve, reject) => {
      exec(`python ${pythonScriptPath}`, (error, stdout, stderr) => {
        if (error) {
          console.log(error);
          reject(error)
        } else if (stderr) {
          console.log(stderr);
          reject(stderr)
        } else {
          resolve(stdout);
        }
      });
    });
    console.log(`Python script output: ${result}`);
    return 'ok';
  } catch (error) {
    console.error(`Error executing Python script: ${error}`);
    throw error; // 可以选择重新抛出错误或返回特定的值
  }
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})